package com.meirimoney.task;

import java.io.IOException;

import com.meirimoney.business.User;
import com.meirimoney.sdk.models.AccessToken;
import com.meirimoney.service.MeiRiMoneyClient;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class SignInThreadRunnable implements Runnable
{

	private Context context;

	private Handler mainThreadHandler = null;

	public SignInThreadRunnable(Context context, Handler h)
	{
		this.mainThreadHandler = h;
		this.context = context;
	}

	public void run()
	{
		Integer status = SignInThreadRunnable.NORMAL;
		try
		{
			status = this.signIn(User.get(this.context));
		} catch (IOException e)
		{
			status = SignInThreadRunnable.NETWORKABERRANT;
		} catch (Exception e)
		{
			status = SignInThreadRunnable.SYSTEMABERRANT;
		}
		Message msg = mainThreadHandler.obtainMessage();
		Bundle bd = new Bundle();
		bd.putInt("status", status);
		msg.setData(bd);
		this.mainThreadHandler.sendMessage(msg);
	}

	/***
	 * 登录系统
	 * 
	 * @param context
	 *            当前执行操作的上下文
	 * @throws IOException
	 *             网络异常
	 */
	private Integer signIn(User user) throws IOException
	{
		AccessToken token = MeiRiMoneyClient.Instance.login(user.getUserId());
		if (null != token)
		{
			user.setToken(token);
			return SignInThreadRunnable.NORMAL;
		} else
		{
			return SignInThreadRunnable.NETWORKABERRANT;
		}
	}

	/**
	 * 正常状态
	 */
	public static final int NORMAL = 1;

	/**
	 * 网络异常
	 */
	public static final int NETWORKABERRANT = 2;

	/**
	 * 系统异常
	 */
	public static final int SYSTEMABERRANT = 3;
}
